<?php

namespace app\api\controller\v50;

use app\aliyun\controller\AliyunPhone;
use app\aliyun\controller\AliyunRtc;
use app\api\controller\v2\Auth;
use app\astrologer\lib\AstrPush;
use app\chat\LiveMessage;
use app\common\cachemodel\consult\AppUserConsultGift;
use app\common\cachemodel\live\LiveGift;
use app\common\cachemodel\OrdersLib;
use app\common\cachemodel\ZhunleUserAccount;
use app\common\cachemodel\ZhunleUserAccountRecord;
use app\common\cachemodel\zl8\Zl8UserChatReservationRecord;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\cachemodel\ZlcrAstr;
use app\common\cachemodel\ZlcrAstrAccount;
use app\common\lib\Util;
use app\zyhsapi\model\ZyhsConsultChatRecord;
use app\zyhsapi\model\ZyhsConsultChatRecordAstr;
use app\zyhsapi\model\ZyhsConsultChatRecordDetails;
use app\zyhsapi\model\ZyhsConsultChatRtcRecord;
use app\zyhsapi\model\ZyhsConsultRtcUserBenefits;
use think\Db;
use think\response\Json;

class UserConsultChat extends Auth
{
    private $appType2 = 2;

    /**
     * 赠送礼物
     * @return \think\response\Json
     */
    public function sendGift()
    {
        $astrId = input('astr_id/d', 0);
        $giftId = input('gift_id/d', 0);
        $num = input('num/d', 0);
        $password = input('password/s', '');
        if (!$astrId || !$giftId || $num < 1)
        {
            return show(config('code.error'), '请求异常，请刷新后重新操作～');
        }
        if (Util::commentCheck($this->user['id'], ['action' => 'sendGift', 'astr_id' => $astrId, 'gift_id' => $giftId, 'num' => $num, 'password' => $password], 5))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $giftInfo = (new LiveGift())->getInfoById($giftId);
        if (!$giftInfo)
        {
            return show(config('code.error'), '礼物信息不存在～');
        }
        $consultAccountInfo = (new Zlcr3ConsultAccount())->getInfoById($astrId);
        $isConsult = $consultAccountInfo && $consultAccountInfo['consult_status'] === 1 ? 1 : 0;
        if (!$isConsult)
        {
            return show(config('code.error'), '服务异常，咨询师不存在～');
        }
        $astrInfo = (new ZlcrAstr())->getInfoById($astrId);
        $consultChatIdModel = new ZyhsConsultChatRecord();
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $chatId = $consultChatIdModel->getChatIdByAstrId($this->appType2, $this->user['id'], $astrId);
        $nowTime = $this->request->time();
        if (!$chatId)
        {
            $insertData = [
                'app_type' => $this->appType2,
                'uid' => $this->user['id'],
                'astr_id' => $astrId,
                'last_chat_detail_id' => 0,
                'last_chat_detail_time' => 0,
                'create_time' => $nowTime,
            ];
            // 创建新的会话
            $chatId = $consultChatIdModel->SaveData($insertData);
        }
        // 计算 礼物需要准币数
        $giftCoin = $giftInfo['coin'] * $num;
        $zhunleUserAccountModel = new ZhunleUserAccount();
        $userCoinInfo = $zhunleUserAccountModel->getUserCoinFromCache($this->user['id']);
        $zhunleUserAccountModel->verifyCoinPay($userCoinInfo, $password, $giftCoin);
        $coinNum = $userCoinInfo['balance'] ?? 0;// 准币余额
        // 扣除 准币
        $coinNum = $coinNum - $giftCoin;
        $consume_price = $userCoinInfo['consume_price'] + OrdersLib::getOrderCoinTotalAmount($giftCoin);
        $consume_coin = $userCoinInfo['consume_coin'] + $giftCoin;
        //更新用户钱包金额
        $zhunleUserAccountModel->UpdateData($this->user['id'], ['balance' => $coinNum, 'consume_price' => $consume_price, 'consume_coin' => $consume_coin, 'update_time' => $nowTime], ['uid' => $this->user['id']]);
        // 写入 用户 准币流水
        $accountExtend = [
            'astr_id' => $astrId,
            'astr_name' => $astrInfo['nickname'],
            'gift_id' => $giftId,// 赠送礼物ID
            'gift_name' => $giftInfo['name'],   // 礼物名字
            'num' => $num,  // 赠送数量
        ];
        $insertData = [
            'status' => 1,
            'account' => 0,
            'uid' => $this->user['id'],
            'consumer_type' => 2,
            'order_type' => 120,    // 120=>打赏咨询师礼物
            'gid' => 0,
            'pray_date' => 0,
            'total_amount' => $giftCoin / 10,
            'coin_num' => $giftCoin,
            'balance' => $coinNum,
            'order_id' => '',
            'trade_type' => 4,
            'create_time' => $nowTime,
            'extend' => '',
        ];
        //增加准币明细记录
        $zhunleUserAccountRecordModel = new ZhunleUserAccountRecord();
        $crid = $zhunleUserAccountRecordModel->SaveData($this->user['id'], $insertData);
        // 写入 占星师收入流水
        // 1、 计算咨询师收益 连线 （准币收益 + 连线礼包收益）* 收益百分比
        $totalPrice = ($giftCoin * 0.7) / 10; // 占星师 收入70%
        $earnings = Util::getAfterTaxAmount($totalPrice); // 收益
        $teamId = $astrInfo['team_id'] ?? 0;
        // 2、 写入 占星师 收益
        (new ZlcrAstrAccount())->astrGiftEarningsSend([
            'earning' => $earnings,
            'total_amount' => $insertData['total_amount'], // 用户支付 时间金额
            'astr_id' => $astrId,
            'type' => 1,    // 1=>入账 2=>提现 3=>后台人员回复的用户内容 4=>问答冻结  5=>问答解冻
            'gid' => $crid,
            'proportion' => 0.7,
            'team_id' => $teamId,
        ], $this->appType2);
        $consultMsgData = [
            'chat_id' => $chatId,
            'app_type' => $this->appType2,
            'uid' => $this->user['id'],
            'astr_id' => $astrId,
            'type' => 2,    //  1=>APP消息 2=>用户发送消息
            'title' => '',
            'content' => '', // 提问问题
            'data_type' => 11,   // 1=>普通消息  2=>图片  3=>语音咨询消息  4=>咨询问题  5=>咨询问题答案 6=>问答悬赏问题回复 7=>问答悬赏追问已回复 8=>用户发送星盘信息  9=>预约咨询 10=>求打赏礼物 11=>用户打赏礼物
            'extend' => [
                'intercept_tips' => '',
                'gift_data' => [
                    'gift_id' => $giftId,// 赠送礼物ID
                    'gift_name' => $giftInfo['name'],   // 礼物名字
                    'num' => $num,  // 赠送数量
                    'earnings' => $earnings, // 收益
                    'cr_id' => $crid,   // 用户准币流水ID
                ],
            ],  //  语音咨询消息 ｜ 图片信息 | 内容拦截信息
            'pid' => 0, // 待更新
            'create_time' => $nowTime,
        ];
        $resData = $consultChatRecordDetailsModel->SaveData($chatId, $consultMsgData);
        if ($resData)
        {   // 更新用户端 最后咨询信息
            $consultChatIdModel->updateData($chatId, [
                'uid' => $this->user['id'],
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTime,
            ], $this->appType2);
            $accountExtend['chat_detail_id'] = $resData['id'];
            $zhunleUserAccountRecordModel->UpdateData($this->user['id'], $crid, ['extend' => json_encode($accountExtend, JSON_UNESCAPED_UNICODE)], ['id' => $crid]);
            // 更新咨询师端 最后咨询信息
            $zlcr3ConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
            $astrChatInfo = $zlcr3ConsultChatRecordAstrModel->getUserAstrChatInfo($this->appType2, $this->user['id'], $astrId);
            $zlcr3ConsultChatRecordAstrModel->userSendUpdate($this->appType2, $this->user['id'], $astrId, [
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTime,
                'unread_num' => Db::raw('unread_num + 1'),
            ]);
            $resData1 = current($consultChatRecordDetailsModel->userDataListResert([$resData], [], $this->user, $this->appType2));
            // 判断咨询师是否在线
            if (LiveMessage::getUserIsOnline(2, $astrId))
            {   // 向 咨询师发送消息
                $astrData2 = current($consultChatRecordDetailsModel->astrDataListResert([$resData], [], $this->user, $this->appType2));
                LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                    'msg_type' => 2,
                    'app_type' => $this->appType2,
                    'uid' => $this->user['id'],
                    'num' => $astrChatInfo['delay_num'],
                    'msg_data' => $astrData2,
                ]);
            }
            $resData1['time_des'] = '';
            $resData1['intercept_tips'] = '';
            $resData1['transaction_id'] = $crid;

            $pushAlert = '[礼物打赏]';
            $pushData = [
                'action' => 'extend',
                'target' => 'local',
                'link' => "chat?id={$this->user['id']}&app_type={$this->appType2}",
                'pop_msg' => json_encode([
                    'avatar' => $this->user['avatar'],
                    'name' => $this->user['nickname'],
                    'msg' => $pushAlert,
                    'target' => 'local',
                    'link' => "chat?id={$this->user['id']}&app_type={$this->appType2}",
                    'uid' => $this->user['id'],
                    'app_type' => $this->appType2,
                ], JSON_UNESCAPED_UNICODE),
            ];
            (new AstrPush())->pushUserMsg($astrId, $pushAlert, $pushData);

            return show(config('code.success'), '请求成功', $resData1);
        }

        return show(config('code.error'), '服务异常，请稍后再试～');
    }

    /**
     * 发起 RTC连麦 交互请求
     * @return Json
     * @throws \Exception
     */
    public function requestRtcInteraction()
    {
        $astrId = input('astr_id/d', 0);
        $giftId = input('gift_id/d', 0);
        $zlcrAstrModel = new ZlcrAstr();
        if (Util::commentCheck($this->user['id'], ['action' => 'requestRtcInteraction', 'astr_id' => $astrId, 'gift_id' => $giftId], 5))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $consultAccountInfo = (new Zlcr3ConsultAccount())->getInfoById($astrId);
        $isConsult = $consultAccountInfo && $consultAccountInfo['consult_status'] === 1 ? 1 : 0;
        if (!$isConsult)
        {
            return show(config('code.error'), '服务异常，咨询师不存在～');
        }
        // 获取当前用户 咨询状态
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $userNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(1, $this->appType2, $this->user['id']);
        if ($userNowConsultRtcInfo)
        {   // 用户正在连麦中
            return show(config('code.error'), '当前正在连线中，不可重复连线～');
        }
        // 咨询师营业状态判断 不是ws在线状态
        if ($consultAccountInfo['status'] !== 1)
        {   // 咨询师休息 了
            return show(config('code.error'), '咨询师暂时不在，稍侯再来吧~');
        }
        if ($giftId)
        {
            $userGiftIngo = (new AppUserConsultGift())->getInfoById($giftId);
            if (!$userGiftIngo || $userGiftIngo['uid'] !== $this->user['id'] || $userGiftIngo['status'] !== 1 || $userGiftIngo['duration_minute'] - $userGiftIngo['use_minute'] <= 0)
            {
                return show(config('code.error'), '服务异常，礼包不存在或已过期～');
            }
            if ($userGiftIngo['end_time'] > 0 && $userGiftIngo['end_time'] < $this->request->time())
            {
                return show(config('code.error'), '服务异常，礼包已过期～');
            }
        }
        // 获取当前咨询师 咨询状态
        $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $this->appType2, $astrId);
        if ($astrNowConsultRtcInfo)
        {   // 咨询师 当前正在 连麦中 或者 已经有连麦请求
            $extend = [
                'rtc_data' => [
                    'rtc_id' => 0,
                    'status' => 5,  //【rtc_id=0该字段数据生效】 1=>申请中待接听  2=>咨询师未响应  3=>咨询师拒绝  4=>连线已取消 5=>咨询师忙线中
                ],
                'version' => $this->headers['version'] ?? '',
            ];
            $isRtc = false;
        } else
        {
            $extend = [
                'rtc_data' => [
                    'rtc_id' => 0,
                    'status' => 1,  //【rtc_id=0该字段数据生效】 1=>申请中待接听  2=>咨询师未响应  3=>咨询师拒绝  4=>连线已取消 5=>咨询师忙线中
                ],
                'version' => $this->headers['version'] ?? '',
            ];
            $isRtc = true;
        }
        $consultChatIdModel = new ZyhsConsultChatRecord();
        $chatId = $consultChatIdModel->getChatIdByAstrId($this->appType2, $this->user['id'], $astrId);
        $nowTimw = $this->request->time();
        if (!$chatId)
        {
            $insertData = [
                'app_type' => $this->appType2,
                'uid' => $this->user['id'],
                'astr_id' => $astrId,
                'last_chat_detail_id' => 0,
                'last_chat_detail_time' => 0,
                'create_time' => $nowTimw,
            ];
            // 创建新的会话
            $chatId = $consultChatIdModel->SaveData($insertData);
        }

        $consultMsgData = [
            'chat_id' => $chatId,
            'app_type' => $this->appType2,
            'uid' => $this->user['id'],
            'astr_id' => $astrId,
            'type' => 2,    //  1=>APP消息 2=>用户发送消息
            'title' => '',
            'content' => '', // 提问问题
            'data_type' => 3,   // 1=>普通消息  2=>图片  3=>语音咨询消息
            'extend' => $extend,  //  语音咨询消息 ｜ 图片信息
            'pid' => 0, // 待更新
            'create_time' => $nowTimw,
        ];

        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $resData = $consultChatRecordDetailsModel->SaveData($chatId, $consultMsgData);
        if ($resData)
        {
            $consultChatIdModel->updateData($chatId, [
                'uid' => $this->user['id'],
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTimw,
            ], $this->appType2);
            // 更新咨询师端 最后咨询信息
            (new ZyhsConsultChatRecordAstr())->userSendUpdate($this->appType2, $this->user['id'], $astrId, [
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTimw,
                'unread_num' => Db::raw('unread_num + 1'),
                'call_num' => Db::raw('call_num + 1'),
            ]);

            $resData2 = current($consultChatRecordDetailsModel->userDataListResert([$resData], [], $this->user, $this->appType2));
            $resData2['rtc_auth'] = null;
            if ($isRtc)
            {   // 更新用户端 最后咨询信息
                $astrInfo = $zlcrAstrModel->getInfoById($astrId, ['avatar', 'nickname', 'tel']);
                $userNowConsultRtcInfo = [
                    'id' => 0, // 连麦ID    ID==0 为邀请连麦  否则为主播接受连麦
                    'rtc_sign' => uniqid('', false),
                    'app_type' => $this->appType2,
                    'astr_id' => $astrId,
                    'nickname' => $astrInfo['nickname'] ?? '',
                    'avatar' => $astrInfo['avatar'] ?? '',
                    'status' => 1,  // 当前连麦状态 1=>等待咨询师接受 2=>咨询师接受开始连麦中 3=>连麦成功 连麦中
                    'request_time' => $this->request->time(),   // 邀请咨询师连麦时间
                    'chat_id' => $resData['id'],
                    'gift_id' => $giftId,
                ];
                $consultChatRtcRecordModel->saveNowRtcDataToCache(1, $this->appType2, $this->user['id'], $userNowConsultRtcInfo, false, $resData['id']);
                $astrNowConsultRtcInfo = [
                    'id' => 0, // 连麦ID    ID==0 为邀请连麦  否则为主播接受连麦
                    'rtc_sign' => $userNowConsultRtcInfo['rtc_sign'],
                    'app_type' => $this->appType2,
                    'uid' => $this->user['id'],
                    'nickname' => $this->user['nickname'] ?? '',
                    'avatar' => $this->user['avatar'] ?? '',
                    'uen' => $this->user['uen'] ?? '',
                    'status' => 1,  // 当前连麦状态 1=>等待咨询师接受 2=>咨询师接受开始连麦中 3=>连麦成功 连麦中
                    'request_time' => $this->request->time(),   // 邀请咨询师连麦时间
                    'chat_id' => $resData['id'],
                    'gift_id' => $giftId,
                ];
                $astrNowConsultRtcInfo['recode_datas'] = $consultChatRecordDetailsModel->getRtcInitRecodeInfo($chatId);
                $consultChatRtcRecordModel->saveNowRtcDataToCache(2, $this->appType2, $astrId, $astrNowConsultRtcInfo, false, $resData['id']);
                // 判断咨询师是否在线
                if (LiveMessage::getUserIsOnline(2, $astrId))
                {   // 在线
                    $astrData = current($consultChatRecordDetailsModel->astrDataListResert([$resData], [], $this->user, $this->appType2));
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                        'msg_type' => 2,
                        'app_type' => $this->appType2,
                        'uid' => $this->user['id'],
                        'msg_data' => $astrData,
                    ]);
                    $newUserWelfare = (new ZyhsConsultRtcUserBenefits())->getConsultRtcUserBenefits($this->appType2, $this->user['id']);
                    $freeRtcMin = $newUserWelfare['min'] ?? 0;
                    $desc = $freeRtcMin ? sprintf("申请语音咨询(免费%d分钟)…", $freeRtcMin) : '申请语音咨询…';
                    $voiceCallData = [
                        'chat_id' => $resData['id'],
                        'app_type' => $this->appType2,
                        'uid' => $this->user['id'],
                        'avatar' => $this->user['avatar'],
                        'nickname' => $this->user['nickname'],
                        'status' => 1,
                        'desc' => $desc,
                    ];
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_VOICE_CONSULT_CALL, $voiceCallData);
                } else
                {   // 咨询师ws不在线
                    AliyunPhone::singleCallByTts($astrInfo['tel'], 'TTS_282195080');
                }
                // 2分钟后 判断状态是否还是待接听 状态 如果是待接听状态 则取消连线
                Util::queuePush('rtc_consult_accept_check', ['id' => $resData['id']], 120);
                // 创建订阅回调
                $aliyunRtcModel = new AliyunRtc();
                $subscribeChannelId = 'consult2_' . $resData['id'];
                $signToken = 'zhunle-' . mt_rand(1000, 9999) . '-' . $astrNowConsultRtcInfo['rtc_sign'];
                $result = $aliyunRtcModel->createEventSubscribe($subscribeChannelId, $signToken, 'consult_subscribe_call_back_url');
                if ($result['code'] !== 200)
                {
                    return show(config('code.error'), $result['msg']);
                }
                $aliyunRtcModel->RtcStartRecordTask($subscribeChannelId, $subscribeChannelId);
                // 获取 用户 rtc 授权
                $userRtcAuth = $aliyunRtcModel->getRtcAuth('user_' . $this->user['id'], $subscribeChannelId, 'sub');
                $resData2['rtc_auth'] = $userRtcAuth;
            }
            $pushData = ['action' => 'extend', 'target' => 'local', 'link' => 'empty',];
            (new AstrPush())->pushUserMsg($astrId, '你收到新的咨询连线申请，点击查看', $pushData);
            $resData2['time_des'] = '';
            //  增加咨询师 可回复次数
            $zyhsConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
            $astrChatId = $zyhsConsultChatRecordAstrModel->getIdByAstrIdAndUid($astrId, $this->appType2, $this->user['id']);
            $astrChatIdInfo = $zyhsConsultChatRecordAstrModel->getInfoById($astrChatId);
            if ($astrChatIdInfo['call_delay_num'] < 3)
            {
                $astrChatIdInfo['call_delay_num'] = 3;
                $zyhsConsultChatRecordAstrModel->UpdateData($astrChatId, $astrId, [
                    'call_delay_num' => 3,
                ]);
            }
            $this->handleReservationStatus();
            return show(config('code.success'), '请求成功', $resData2);
        }

        return show(config('code.error'), '服务异常，请稍后再试～');
    }

    /**
     * 处理预约状态
     * @return void
     */
    private function handleReservationStatus()
    {
        try
        {
            // 获取当前用户的预约记录
            $zl8UserChatReservationRecordModel = new Zl8UserChatReservationRecord();
            $userReservationList = $zl8UserChatReservationRecordModel->getUserReservationList($this->user['id']);
            if ($userReservationList)
            {
                $ids = array_keys($userReservationList);
                $dateTmp = $this->request->time();
                $userReservationInfo = $zl8UserChatReservationRecordModel->batchGetInfoByIds($ids);
                foreach ($userReservationInfo as $item)
                {
                    //是否为待履约状态
                    if ($item['status'] === $zl8UserChatReservationRecordModel->statusList['wait_keep_promise'])
                    {
                        $beforeHourTmp = $item['h_id'] === 24 ? 23 : $item['h_id'] - 1;
                        $dateTimeTmp = strtotime($item['date'] . ' ' . $item['h_id'] . ':00');
                        $beforeDateTimeTmp = strtotime($item['date'] . ' ' . $beforeHourTmp . ':00');
                        //在预约时间段内处理预约状态
                        if ($dateTmp >= $beforeDateTimeTmp && $dateTmp < $dateTimeTmp)
                        {
                            $res = $zl8UserChatReservationRecordModel->updateData($item['id'], ['status' => $zl8UserChatReservationRecordModel->statusList['keep_promise'], 'update_time' => $dateTmp]);
                            if ($res)
                            {
                                $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
                                $chatDetail = $consultChatRecordDetailsModel->getInfoById($item['char_id']);
                                $chatDetail['extend'] ['reservation_info']['status'] = $zl8UserChatReservationRecordModel->statusList['keep_promise'];
                                $consultChatRecordDetailsModel->UpdateData($chatDetail['id'], ['extend' => $chatDetail['extend']]);
                            }
                        }
                    }
                }
            }
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()用户连线,履约处理异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
        }
    }

    /**
     * 挂断连线｜取消连线（未接听）
     * @return Json
     * @throws \Exception
     */
    public function rtcCancel()
    {
        $chatDetailid = input('id/d', 0);
        $type = input('type/d', 0);
        $reason = input('reason/s', '');
        if (!$chatDetailid)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (Util::commentCheck($this->user['id'], ['action' => 'rtcCancel', 'id' => $chatDetailid, 'type' => $type, 'reason' => $reason], 5))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        // 获取当前用户 咨询状态
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $userNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(1, $this->appType2, $this->user['id']);
        $astrWsIsOnline = false;
        if ($userNowConsultRtcInfo)
        {   // 用户正在连麦中
            $res = $consultChatRtcRecordModel->setRtcPadlock($chatDetailid);
            if (!$res)
            {
                return show(config('code.error'), '连线状态异常，请稍后再试～');
            }
            if ((int)$userNowConsultRtcInfo['chat_id'] === $chatDetailid)
            {   // 删除当前连麦 信息
                $astrId = (int)$userNowConsultRtcInfo['astr_id'];
                // 更新当前连麦信息
                $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $this->appType2, $astrId);
                if ($astrNowConsultRtcInfo && (int)$astrNowConsultRtcInfo['chat_id'] === $chatDetailid)
                {   // 当前连麦数据正确
                    if (LiveMessage::getUserIsOnline(2, $astrId))
                    {   //  隐藏 电话提醒
                        $astrWsIsOnline = true;
                        $voiceCallData = [
                            'chat_id' => $chatDetailid,
                            'app_type' => $this->appType2,
                            'uid' => $this->user['id'],
                            'avatar' => $this->user['avatar'],
                            'nickname' => $this->user['nickname'],
                            'status' => 0,
                            'desc' => '',
                        ];
                        LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_VOICE_CONSULT_CALL, $voiceCallData);
                    }
                }
                // 删除 频道订阅 与 当前RTC房间
                (new AliyunRtc())->rmEventSubAndDelRtcChannel('consult2_' . $chatDetailid);

                $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailid);
                if ($userNowConsultRtcInfo['id'])
                {   // 连线成功
                    $data = $consultChatRtcRecordModel->rtcConsultHangUp($chatDetail, $reason, 1, 1);
                    if ($data['status'])
                    {   // 返回 打点信息
                        // $data['data']['event_marking_data'] = $data['event_marking_data'];
                        $consultChatRtcRecordModel->loseOperatorLicense($chatDetailid);
                        return show(config('code.success'), '请求成功', $data['data']);
                    }

                    $consultChatRtcRecordModel->delNowRtcDataByCache(1, $this->appType2, $this->user['id'], $chatDetailid); // 删除当前连麦信息
                    $consultChatRtcRecordModel->loseOperatorLicense($chatDetailid);
                    return show(config('code.error'), $data['msg']);
                }
                // 未连线成功
                $consultChatRtcRecordModel->delNowRtcDataByCache(1, $this->appType2, $this->user['id'], $chatDetailid);
                if ($astrNowConsultRtcInfo && (int)$astrNowConsultRtcInfo['uid'] === $this->user['id'])
                {
                    $consultChatRtcRecordModel->delNowRtcDataByCache(2, $this->appType2, $astrId, $chatDetailid);
                }
                $chatDetail['extend']['rtc_data']['status'] = 4;  //【rtc_id=0该字段数据生效】 1=>申请中待接听  2=>咨询师未响应  3=>咨询师拒绝  4=>连线已取消 5=>咨询师忙线中
                // 更新数据
                $consultChatRecordDetailsModel->UpdateData($chatDetailid, ['extend' => $chatDetail['extend']]);
                $resData2 = current($consultChatRecordDetailsModel->userDataListResert([$chatDetail], [], $this->user, $this->appType2));

                $consultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
                $userChatId = $consultChatRecordAstrModel->getIdByAstrIdAndUid($astrId, $this->appType2, $this->user['id']);
                if ($userChatId)
                {
                    $userChatInfo = $consultChatRecordAstrModel->getInfoById($userChatId, 'unread_num');
                    if ($userChatInfo['unread_num'] === 0)
                    {   // 更新咨询师端 最后咨询信息
                        $consultChatRecordAstrModel->userSendUpdate($this->appType2, $this->user['id'], $astrId, [
                            'unread_num' => Db::raw('unread_num + 1'),
                        ]);
                    }
                }

                if ($astrWsIsOnline)
                {
                    $astrData = current($consultChatRecordDetailsModel->astrDataListResert([$chatDetail], [], $this->user, $this->appType2));
                    LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                        'msg_type' => 2,
                        'app_type' => $this->appType2,
                        'uid' => $this->user['id'],
                        'msg_data' => $astrData,
                    ]);
                }
                $resData2['event_marking_data'] = null;
                $consultChatRtcRecordModel->loseOperatorLicense($chatDetailid);
                return show(config('code.success'), '取消成功', $resData2);
            }
            $consultChatRtcRecordModel->loseOperatorLicense($chatDetailid);
            return show(config('code.error'), '语音连线咨询状态异常，请稍后再试～');
        }

        return show(config('code.error'), '语音连线咨询状态异常，请稍后再试～');
    }
}